<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PDF转JPG批量处理系统</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <header>
        <h1>PDF转JPG批量处理系统</h1>
        <p>批量转换PDF为JPG，按规则重命名并整理文件夹结构</p>
        <p>
          使用说明: 确保已配置文件夹路径并
          <strong style="color: yellow">保存配置</strong>
          后点击"开始转换"
        </p>
      </header>

      <main>
        <section class="config-section">
          <h2>配置设置</h2>
          <div class="form-group">
            <label for="sourceDir"
              >源文件夹路径:
              <span class="tips"
                >（例如：C:\Users\Administrator\Desktop\新建文件夹\411623104202郭楼村）</span
              >
            </label>
            <input
              type="text"
              id="sourceDir"
              placeholder="请输入源文件夹路径"
            />
          </div>

          <div class="form-group">
            <label for="targetDir"
              >目标文件夹路径:
              <span class="tips"
                >（例如：C:\Users\Administrator\Desktop\新建文件夹\转换后）</span
              >
            </label>
            <input
              type="text"
              id="targetDir"
              placeholder="请输入目标文件夹路径"
            />
          </div>

          <div class="form-group">
            <label for="resolution">转换分辨率 (DPI):</label>
            <input
              type="number"
              id="resolution"
              min="72"
              max="600"
              value="200"
            />
          </div>

          <section class="naming-rules">
            <h2>文件命名规则</h2>
            <button class="btn" id="addRuleRow">+ 新增规则</button>
            <div class="rules-container">
              <table id="namingRulesTable">
                <thead>
                  <tr>
                    <th>原始文件名关键字</th>
                    <th>新文件名前缀</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody id="namingRulesTableBody">
                  <!-- 命名规则将通过JS动态填充为可编辑行 -->
                </tbody>
              </table>
            </div>
          </section>

          <!-- <button class="btn primary" id="saveConfig">保存配置</button> -->
        </section>

        <section class="action-section">
          <h2>执行转换</h2>
          <div class="status">
            <div class="status-indicator" id="statusIndicator"></div>
            <span id="statusText">准备就绪</span>
          </div>

          <div class="stats" id="statsContainer">
            <div class="stat-item">
              <span class="stat-label">文件夹:</span>
              <span class="stat-value" id="foldersCount">0</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">PDF文件:</span>
              <span class="stat-value" id="pdfsCount">0</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">总页数:</span>
              <span class="stat-value" id="pagesCount">0</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">图片文件:</span>
              <span class="stat-value" id="imagesCount">0</span>
            </div>
          </div>

          <button class="btn primary large" id="startConversion">
            开始转换
          </button>
        </section>

        <section class="log-section">
          <h2>转换日志</h2>
          <div class="log-container">
            <pre id="logContent">等待开始转换...</pre>
          </div>
          <button class="btn" id="refreshLog">刷新日志</button>
          <button class="btn" id="clearLog">清除日志</button>
        </section>
      </main>

      <footer>
        <p>PDF转JPG批量处理系统 v1.0 &copy; 林夕小哥哥</p>
      </footer>
    </div>

    <script>
      // DOM元素
      const sourceDirInput = document.getElementById("sourceDir");
      const targetDirInput = document.getElementById("targetDir");
      const resolutionInput = document.getElementById("resolution");
      const saveConfigBtn = document.getElementById("saveConfig");
      const startConversionBtn = document.getElementById("startConversion");
      const refreshLogBtn = document.getElementById("refreshLog");
      const clearLogBtn = document.getElementById("clearLog");
      const logContent = document.getElementById("logContent");
      const statusIndicator = document.getElementById("statusIndicator");
      const statusText = document.getElementById("statusText");
      const rulesTable = document.querySelector("#namingRulesTable tbody");
      const rulesTableBody = document.getElementById("namingRulesTableBody");

      // 状态元素
      const foldersCount = document.getElementById("foldersCount");
      const pdfsCount = document.getElementById("pdfsCount");
      const pagesCount = document.getElementById("pagesCount");
      const imagesCount = document.getElementById("imagesCount");

      // 初始化
      async function init() {
        // 加载配置
        try {
          const response = await fetch("/config");
          const config = await response.json();

          sourceDirInput.value = config.sourceDir;
          targetDirInput.value = config.targetDir;
          resolutionInput.value = config.resolution;

          // 填充命名规则表
          for (const [key, value] of Object.entries(config.namingRules)) {
            const row = document.createElement("tr");
            row.innerHTML = `
              <td><input type="text" class="rule-key" value="${key}" /></td>
              <td><input type="text" class="rule-value" value="${value}" /></td>
              <td><button class="btn small delete-row">删除</button></td>
            `;
            rulesTableBody.appendChild(row);
          }
        } catch (error) {
          console.error("加载配置失败:", error);
        }
      }

      // 添加“新增规则”按钮事件监听器
      document.getElementById("addRuleRow").addEventListener("click", () => {
        const row = document.createElement("tr");
        row.innerHTML = `
          <td><input type="text" class="rule-key" /></td>
          <td><input type="text" class="rule-value" /></td>
          <td><button class="btn small delete-row">删除</button></td>
        `;
        document.getElementById("namingRulesTableBody").appendChild(row);

        // 获取 .rules-container 容器
        const container = document.querySelector(".rules-container");

        // 设置其 scrollTop 为最大值，实现底部对齐
        container.scrollTop = container.scrollHeight;
      });

      // 添加“删除行”事件委托（因为行是动态生成的）
      document
        .getElementById("namingRulesTableBody")
        .addEventListener("click", (e) => {
          if (e.target && e.target.classList.contains("delete-row")) {
            e.target.closest("tr").remove();
          }
        });

      // 保存配置
      // saveConfigBtn.addEventListener("click", handleSave);

      // 保存配置处理函数
      async function handleSave() {
        // 获取输入值
        const sourceDir = sourceDirInput.value.trim();
        const targetDir = targetDirInput.value.trim();
        const resolution = resolutionInput.value.trim();

        // 表单验证：检查是否为空
        if (!sourceDir || !targetDir || !resolution) {
          alert("请填写所有字段：源文件夹路径、目标文件夹路径和转换分辨率");
          return;
        }

        // 检查分辨率是否为合法数字
        if (isNaN(resolution) || resolution <= 0) {
          alert("请输入有效的转换分辨率（正整数）");
          return;
        }

        // 获取文件命名规则
        const rules = {};
        const rows = document.querySelectorAll("#namingRulesTableBody tr");

        rows.forEach((row) => {
          const keyInput = row.querySelector(".rule-key");
          const valueInput = row.querySelector(".rule-value");
          if (keyInput && valueInput && keyInput.value.trim()) {
            rules[keyInput.value.trim()] = valueInput.value.trim();
          }
        });

        const config = {
          sourceDir: sourceDirInput.value,
          targetDir: targetDirInput.value,
          resolution: resolutionInput.value,
          namingRules: rules,
        };

        try {
          const response = await fetch("/config", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(config),
          });

          if (response.ok) {
            console.log("配置保存成功!");
          } else {
            alert("保存配置失败");
          }
        } catch (error) {
          console.error("保存配置失败:", error);
          alert("保存配置失败");
        }
      }

      // 开始转换
      startConversionBtn.addEventListener("click", async () => {
        setStatus("processing", "转换进行中...");

        await handleSave()

        const conversionData = {
          sourceDir: sourceDirInput.value,
          targetDir: targetDirInput.value,
        };

        try {
          const response = await fetch("/convert", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(conversionData),
          });

          const result = await response.json();

          if (result.success) {
            setStatus("success", "转换完成!");

            // 更新统计信息
            foldersCount.textContent = result.stats.folders;
            pdfsCount.textContent = result.stats.pdfs;
            pagesCount.textContent = result.stats.pages;
            imagesCount.textContent = result.stats.images;

            // 刷新日志
            refreshLog();
          } else {
            setStatus("error", `转换失败: ${result.error}`);
          }
        } catch (error) {
          setStatus("error", `转换失败: ${error.message}`);
        }
      });

      // 刷新日志
      refreshLogBtn.addEventListener("click", refreshLog);

      // 清除日志
      clearLogBtn.addEventListener("click", async () => {
        logContent.textContent = "日志已清除";
      });

      // 设置状态
      function setStatus(status, message) {
        statusIndicator.className = "status-indicator";
        statusText.textContent = message;

        switch (status) {
          case "processing":
            statusIndicator.classList.add("processing");
            break;
          case "success":
            statusIndicator.classList.add("success");
            break;
          case "error":
            statusIndicator.classList.add("error");
            break;
          default:
            statusIndicator.classList.add("idle");
        }
      }

      // 刷新日志内容
      async function refreshLog() {
        try {
          const response = await fetch("/log");
          const log = await response.text();
          logContent.textContent = log || "暂无日志记录";
        } catch (error) {
          logContent.textContent = "获取日志失败";
        }
      }

      // 初始化应用
      init();
    </script>
  </body>
</html>
